package com.laowang.aspect;

import com.laowang.constant.CookieConstant;
import com.laowang.constant.RedisConstant;
import com.laowang.exception.SellerAuthorizeException;
import com.laowang.utils.CookieUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by Administrator on 2019/1/26.
 */
@Component
@Aspect
@Slf4j
public class SellerAuthorizeAspect {
    @Autowired
    private StringRedisTemplate template;
    @Pointcut("execution(public * com.laowang.controller.Seller*.*(..))" +
            "!execution(public * com.laowang.controller.sellerInfoController.*(..))")
    public void verify(){};

    public void doVerify(){
        ServletRequestAttributes attributes =(ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //查询cookie
        Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);
        if(cookie==null){
            throw new SellerAuthorizeException();
        }
        String tokenValue = template.opsForValue()
                .get(String.format(RedisConstant.TOKEN_PREFIX,cookie.getValue()));
        if(StringUtils.isEmpty(tokenValue)){
            log.warn("[登录校验] redis中查不到token");
            throw new SellerAuthorizeException();
        }

    }
}
